// 函数组件
import React, { useState, useEffect, useContext } from 'react';
import { Button, Modal, Select, Form, Input, Upload, Switch, DatePicker, message, InputNumber } from 'antd';
import { PlusOutlined, LoadingOutlined } from '@ant-design/icons';
import type { RcFile, UploadFile, UploadProps } from 'antd/es/upload/interface';
import "../css/BannerDialog.less"
import dayjs from 'dayjs';
import customParseFormat from 'dayjs/plugin/customParseFormat';
import getSelectTime from '../../../../utils/date';

// 引入请求api等
import { baseUrl, uploadBanner, modBanner, addBanner } from "../../../../api/operationApi"

// 表格泛型
interface PropsType {
    isModalOpen: boolean
    modStuInfo?: DataType | undefined
    type: string
    currentPage: number
    pageSize: number
    close(): void
    getData(currentPage: number, pageSize: number, keyWord?: string, state?: string, upTime?: string): void
}

// 数据类型
interface DataType {
    carouselId: number,
    carouselTital: string,
    carouselLocation: number, 
    carouselPic: string,
    carouselUpordown: number, // 上架
    carouselUptimeStart: string, //上架时间开始
    carouselIuptimeEnd: string,  // 上架时间结束
    carouselTime: string, // 上架时间
    carouselType: string
}


// 表单布局
const layout = {
    labelCol: {
        span: 8,
    },
    wrapperCol: {
        span: 16,
    },
};

// 表单验证
const validateMessages = {
    required: '${label}必填'
};

// 上传按钮
const uploadButton = (
    <div>
        <PlusOutlined />
        <div
            style={{
                marginTop: 8,
            }}
        >
            Upload
        </div>
    </div>
);


function BannerDialog(props: PropsType) {
    const [form] = Form.useForm();

    const { RangePicker } = DatePicker;
    dayjs.extend(customParseFormat);
    const dateFormat = 'YYYY-MM-DD hh:mm:ss';

    const [imageUrl, setImageUrl] = useState<string>();
    const [showImg, setShowImg] = useState<string>();

    const [title, setTitle] = useState<string>('')

    useEffect(() => {
        if (props.type == 'add') {
            setTitle('添加轮播')
            setShowImg('')
            form.resetFields()
            form.setFieldsValue({
                carouselId: '',
                carouselTital: '',
                carouselUptimeStart: '',
                carouselIuptimeEnd: '',
                shelfTimeInterval: '',
                carouselTime: '',
                carouselUpordown: false,
                carouselPic: '',
                carouselLocation: null,
                carouselType: null
            })
            setImageUrl('')
        } else if (props.type == 'mod') {
            setTitle('编辑轮播')

            //设置字段默认值
            form.setFieldsValue({
                carouselId: props.modStuInfo?.carouselId,
                carouselTital: props.modStuInfo?.carouselTital,
                carouselUptimeStart: props.modStuInfo?.carouselUptimeStart,
                carouselIuptimeEnd: props.modStuInfo?.carouselIuptimeEnd,
                shelfTimeInterval: [dayjs(props.modStuInfo?.carouselUptimeStart, dateFormat), dayjs(props.modStuInfo?.carouselIuptimeEnd, dateFormat)],
                carouselTime: dayjs(props.modStuInfo?.carouselTime, dateFormat),
                carouselUpordown: props.modStuInfo?.carouselUpordown == 0 ? false : true,
                carouselLocation:  props.modStuInfo?.carouselLocation,
                carouselType: props.modStuInfo?.carouselType 
            })
            setShowImg(props.modStuInfo?.carouselPic)

            let url = baseUrl + props.modStuInfo?.carouselPic
            setImageUrl(url)
        }
    }, [props])


    // 1、上传图片
    const beforeUpload = () => {
        return false
    };

    // 上传图片
    const handleChange = async (info: any) => {
        console.log("info", info);
        // 先做判断，根据
        if (info.file.status == 'removed') {
            setImageUrl('')
        } else {
            let binaryData = []
            binaryData.push(info.file)
            const localUrl = window.URL.createObjectURL(new Blob(binaryData, { type: 'img/jpeg' }))
            setImageUrl(localUrl)

            // 发起请求
            let formData = new FormData()
            formData.append("file", info.file)
            let res = await uploadBanner(formData)
            setShowImg(res.data)
        }


    };

    // 2、点击确定
    const onFinish = async (values: any) => {
        if (props.type === 'add') {
            console.log("values", values);
            let carouselTime: string = ''

            if (values.carouselTime != '') {
                carouselTime = getSelectTime(values.carouselTime)
            }
            console.log('%c' + '=========>', 'color: #886CE4;font-weight:bolder', 'carouselTime', carouselTime);

            let carouselUptimeStart: string = getSelectTime(values.shelfTimeInterval[0])
            let carouselIuptimeEnd: string = getSelectTime(values.shelfTimeInterval[1])

            if (carouselTime > carouselIuptimeEnd) {
                message.warning('预设上架时间必须小于结束时间')
                return false
            }

            let res = await addBanner({
                "carouselIuptimeEnd": carouselIuptimeEnd,
                "carouselPic": showImg,
                "carouselTime": carouselTime,
                "carouselTital": values.carouselTital,
                "carouselUpordown": values.carouselUpordown ? 1 : 0,
                "carouselUptimeStart": carouselUptimeStart,
                "carouselType": values.carouselType,
                "carouselLocation": values.carouselLocation
            })
            message.success('增加成功')
            await props.getData(props.currentPage, props.pageSize)
            props.close()

        } else if (props.type === 'mod') {
            let carouselTime: string = getSelectTime(values.carouselTime)
            let carouselUptimeStart: string = getSelectTime(values.shelfTimeInterval[0])
            let carouselIuptimeEnd: string = getSelectTime(values.shelfTimeInterval[1])


            if (carouselTime > carouselIuptimeEnd) {
                message.warning('预设上架时间必须小于结束时间')
                return false
            }

            let res = await modBanner({
                "carouselId": props.modStuInfo?.carouselId,
                "carouselIuptimeEnd": carouselIuptimeEnd,
                "carouselPic": showImg,
                "carouselTime": carouselTime,
                "carouselTital": values.carouselTital,
                "carouselUpordown": values.carouselUpordown ? 1 : 0,
                "carouselUptimeStart": carouselUptimeStart,
                "carouselType": values.carouselType,
                "carouselLocation": values.carouselLocation

            })
            message.success('修改成功')
            await props.getData(props.currentPage, props.pageSize)
            props.close()
        }

    };

    // 点击表单取消
    const cancel = () => {
        props.close()
    }
    // 点击叉叉取消
    const handleCancel = () => {
        props.close()
    };


    return (
        <div className='Dialog'>
            <Modal centered={true} forceRender width={560} title={title} open={props.isModalOpen} footer={null} onCancel={handleCancel} >
                <Form
                    {...layout}
                    name="banner-form"
                    onFinish={onFinish}
                    validateMessages={validateMessages}
                    form={form}
                >
                    <Form.Item
                        name='carouselTital'
                        label="轮播标题"
                        rules={[
                            {
                                required: true,
                            },
                        ]}
                        initialValue={props.modStuInfo?.carouselTital}
                    >
                        <Input placeholder='请输入标题'/>
                    </Form.Item>

                    <Form.Item
                        name='cover'
                        label="封面图片"
                        valuePropName="fileList"  /* 子节点的值的属性 */
                        getValueFromEvent={e => { /* 设置如何将 event 的值转换成字段值 */
                            if (Array.isArray(e)) {
                                return e
                            }
                            return e && e.fileList
                        }}
                    >
                        <Upload
                            name="avatar"
                            listType="picture-card"
                            className="avatar-uploader"
                            showUploadList={false}
                            beforeUpload={beforeUpload}
                            onChange={handleChange}
                        >
                            {imageUrl ? (
                                <img
                                    src={imageUrl}
                                    alt="avatar"
                                    width={50}
                                    height={50}
                                />
                            ) : (
                                uploadButton
                            )}
                        </Upload>
                    </Form.Item>

                    <Form.Item
                        name='carouselLocation'
                        label="位置"
                        rules={[
                            {
                                required: true,
                            },
                        ]}
                        initialValue={props.modStuInfo?.carouselLocation}
                    >
                        <InputNumber  placeholder='位置' min={1} max={10}></InputNumber>
                    </Form.Item>

                    <Form.Item
                        name='carouselType'
                        label="类型"
                        rules={[
                            {
                                required: true,
                            },
                        ]}
                        initialValue={props.modStuInfo?.carouselType}
                    >
                        <Select
                            placeholder='请选择类型'
                            style={{ width: 120 }}
                            allowClear
                            options={[{ value: 'H5', label: 'H5' }, { value: '商品', label: '商品' }, { value: '专区', label: '专区' }]}
                        />
                    </Form.Item>


                    <Form.Item
                        name='shelfTimeInterval'
                        label="上架时间段"
                        rules={[
                            {
                                required: true,
                            }
                        ]}
                    >
                        <RangePicker format={dateFormat} showTime />
                    </Form.Item>

                    <Form.Item
                        name='carouselTime'
                        label="预设上架时间"
                        rules={[
                            {
                                required: true,
                            }
                        ]}
                        initialValue={props.modStuInfo?.carouselTime}
                    >
                        <DatePicker showTime />
                    </Form.Item>

                    <Form.Item
                        name='carouselUpordown'
                        label="上架"
                        valuePropName='checked'
                        initialValue={props.modStuInfo?.carouselUpordown}
                    >
                        <Switch />
                    </Form.Item>


                    <Form.Item
                        wrapperCol={{
                            ...layout.wrapperCol,
                            offset: 8,
                        }}
                    >
                        <Button type="primary" htmlType="submit" className='confirm-btn' >确定</Button>
                        <Button type="primary" onClick={cancel} ghost>取消</Button>
                    </Form.Item>
                </Form>
            </Modal>
        </div>
    )
}

export default BannerDialog